package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.ResizeLinerLayout;
import com.lzx.iteam.widget.kpswitch.util.KeyboardUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangshuai on 14-12-29.
 */
public class LoginActivity extends Activity implements View.OnClickListener {
    private Context mContext;
    private ResizeLinerLayout mRootLayout;
    private ImageView mIvCloudLogo;
    private TextView mTvLoginDesc;
    private EditText mEtLoginCountry, mEtLoginPhoneNumber, mEtLoginPassword;
    private Button mBtnLogin;
    private TextView mTvNoAccount, mTvForgetPassword;

    private AsynHttpClient mAsynClient;
    private PreferenceUtil mPreferenceUtil;
    private String mPasswd;
    private String mPhoneNum;
    private String mCountryCode;
    private Dialog mProgressDialog;
    private AllDialogUtil mDialog;
    public static LoginActivity instance = null;
    private CloudDBOperation mCloudDBOperation;
    private boolean isRegist;

    private String mUserId;
    private String mSecurityKey;
    private String mRongToken;


    public static final int ERROR_PARSE = 2001;
    private static final int ERR_LOGIN = 2002;
    public static final int MSG_LOGIN = 2003;

    private static final int SMALLER = 2004;
    private static final int BIGGER = 2005;
    private static final int MSG_RESIZE = 2006;

    private static final int MSG_GET_EVENT_LIST = 2007;
    private static final int MSG_GET_CLOUD_GROUP_LIST = 2009;

    private static final int MSG_SET_REGISTRATION_ID = 2000;
    private static final int MSG_RONG_TOKEN = 2010;

    /**
     *
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case MSG_LOGIN:  // 登录后
                    handleLoginDone(msg);
                    mPreferenceUtil.save(PreferenceUtil.TEAM_SID, LocalLogin.getInstance().mSid);
                    mPreferenceUtil.save(PreferenceUtil.USER_PHONE, mPhoneNum);
                    mPreferenceUtil.save(PreferenceUtil.USER_PASS, mPasswd);
                    break;
                case MSG_GET_EVENT_LIST:
                    if (msg.arg1 == 0) {
                    }
                    break;
                case MSG_GET_CLOUD_GROUP_LIST:
                    if (msg.arg1 == 0) {
                    }
                    break;
                case MSG_RONG_TOKEN:
                    if (msg.arg1 == 0){
                        try {
                            JSONObject item = ((JSONObject)msg.obj).getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            mRongToken = item.getString("token");
                            connectRongYun();

                        } catch (JSONException e) {
                            Log.e("JSONException",e.toString());
                        }

                    }else{
                        Toast.makeText(mContext, (String) msg.obj,
                                Toast.LENGTH_LONG).show();
                        turnToMainActivity();
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        mContext = this;
        instance = this;
        mDialog = AllDialogUtil.getInstance(this);
        mAsynClient = AsynHttpClient.getInstance(mContext);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mCloudDBOperation = new CloudDBOperation(mContext);
        isRegist = getIntent().getBooleanExtra("regist", false);
        initView();
        saveKeyBoardHeight();
    }

    /**
     * 初始化布局元素
     */
    private void initView() {
        mRootLayout = (ResizeLinerLayout) findViewById(R.id.ll_root);
        mRootLayout.setOnResizeListener(new MyResizeListener());
        mIvCloudLogo = (ImageView) findViewById(R.id.iv_cloud_logo);
        mTvLoginDesc = (TextView) findViewById(R.id.tv_login_desc);
        mEtLoginCountry = (EditText) findViewById(R.id.et_login_country);
        mEtLoginPhoneNumber = (EditText) findViewById(R.id.et_login_phone);
        mEtLoginPhoneNumber.setText(mPreferenceUtil.getString(RegisterActivity.LAST_NUMBER, ""));
        mEtLoginPassword = (EditText) findViewById(R.id.et_login_password);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mTvNoAccount = (TextView) findViewById(R.id.tv_no_account);
        mTvNoAccount.setOnClickListener(this);
        mTvForgetPassword = (TextView) findViewById(R.id.tv_forget_password);
        mTvForgetPassword.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
    }

    /**
     * 获取软键盘的高度并保存
     */
    private void saveKeyBoardHeight(){
        final View decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().
                addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    /**
                     * the result is pixels
                     */
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        decorView.getWindowVisibleDisplayFrame(r);
                        int screenHeight = decorView.getRootView().getHeight();
                        int heightDifference = screenHeight - (r.bottom - r.top);
                        Log.e("KeyboardSize", "KeyboardSize:  " + heightDifference);
                        if (heightDifference > 200) {
                            KeyboardUtil.saveKeyboardHeight(mContext, heightDifference - r.top);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                mPhoneNum = mEtLoginPhoneNumber.getText().toString().trim();
                mPasswd = mEtLoginPassword.getText().toString().trim();

                if (!StringUtil.isMobile(mPhoneNum)) {
                    Toast.makeText(mContext, R.string.validate_china_phone_num,
                            Toast.LENGTH_LONG).show();
                    return;
                } else if (TextUtils.isEmpty(mPasswd) || mPasswd.length() < 6) {
                    Toast.makeText(mContext, R.string.validate_passwd, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                LocalLogin.getInstance().mPhoneNum = mPhoneNum;
                login(LocalLogin.getInstance().mPhoneNum, mPasswd);
                mPreferenceUtil.save(RegisterActivity.LAST_NUMBER, mPhoneNum);
                break;
            case R.id.tv_no_account:
                if (isRegist) {
                    finish();
                } else {
                    Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_forget_password:
                Intent forget = new Intent(LoginActivity.this, ForgetActivity.class);
                startActivity(forget);
                break;
            default:
                break;
        }
    }

    /**
     * 登录
     *
     * @param phoneNum
     * @param passwd
     */
    public void login(String phoneNum, String passwd) {

        TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // add a "a_" prefix in order to distinguish from iPhone
        // TODO 当验证码超过三次时，用dId替换tManager.getDeviceId()，随便改did里面一个数字,超过再改
//        String dId = "10C1221B-BA3E-0CEE-1830-5E35A5F2D034";
//        String devId = "a_" + dId;
        String devId = "a_" + tManager.getDeviceId();
        String osVersion = Constants.getVersionName(this);

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE, phoneNum));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_PASS, passwd));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE, "1"));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NAME, "Android " + android.os.Build.VERSION.RELEASE));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NO, devId));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_APP_VERSION, osVersion));

        httpReqDlgShow();
        LoginMessage loginMsg = new LoginMessage(this, mHandler.obtainMessage(MSG_LOGIN));
        loginMsg.type = 2;
        loginMsg.mParams = mList;
        loginMsg.mApi = AsynHttpClient.API_USER_LOGIN;
        mAsynClient.execUserHttp(loginMsg);
    }


    private void httpReqDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).styleProgress("请稍后...");
            mProgressDialog.setCancelable(false);
            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }
        }

    }

    private void getRongToken(){

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD,LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID,mUserId));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_RONG_TOKEN));
        msg.mApi = AsynHttpClient.API_RONG_CHAT_TOKEN;
        msg.mParams = nvps;
        msg.type = 1;
        AsynHttpClient.getInstance(this).execRongHttp(msg);


    }

    private void connectRongYun(){
        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(mRongToken, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {
                getRongToken();
                Log.d("融云connect", "--onTokenIncorrect");
            }

            /**
             * 连接融云成功
             * @param userid 当前 token
             */
            @Override
            public void onSuccess(String userid) {
                Log.d("融云connect", "--onSuccess" + userid);
                turnToMainActivity();
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d("融云connect", "--onError" + errorCode);
            }
        });
    }

    /**
     * 跳转到主页面
     */
    private void turnToMainActivity(){
        httpReqDlgDismiss();
        mPreferenceUtil.save("isLogin", "yes"); // 登录标识
        mPreferenceUtil.save("Other_login",0);  // 其他设备登录标识
        mPreferenceUtil.save(AsynHttpClient.KEY_RONG_TOKEN,mRongToken);
        Log.d("融云connect_token", mPreferenceUtil.getString(AsynHttpClient.KEY_RONG_TOKEN,"dddd"));
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        LoginActivity.this.finish();
        if (isRegist) {
            RegisterActivity.instance.finish();
        }

    }
    /**
     * 登录 message
     */
    public class LoginMessage extends CcMsgStructure {

        private Context mmContext;

        private android.os.Message mmCallback;


        private PreferenceUtil mPreferenceUtil;

        public LoginMessage(Context context, android.os.Message callback) {
            mmCallback = callback;
            mmContext = context;
            mPreferenceUtil = PreferenceUtil.getInstance(mmContext);
        }

        @Override
        public void onReceive(JSONObject data) {

            try {

                JSONObject result = data.getJSONObject("data");
                LocalLogin.getInstance().mSid = result.getString(AsynHttpClient.KEY_SID_OLD);

                mUserId = result.getString(AsynHttpClient.KEY_NEW_USEID);
                mPreferenceUtil.save(PreferenceUtil.CLIENT_USEID, mUserId);
                if (result.has(PreferenceUtil.CLIENT_SECURITY_KRY)){
                    mSecurityKey = result.getString(PreferenceUtil.CLIENT_SECURITY_KRY);
                    mPreferenceUtil.save(PreferenceUtil.CLIENT_SECURITY_KRY, mSecurityKey);
                }
                Log.i("my_useid", "uid ===   " + mUserId + " securityKey = " + mSecurityKey + " sid == " + LocalLogin.getInstance().mSid);
                Log.d("login", "RegistrationID=" + JPushInterface.getRegistrationID(mmContext));
                setRegistrationId(JPushInterface.getRegistrationID(mmContext));

                if (!TextUtils.isEmpty(LocalLogin.getInstance().mPhoneNum) && !TextUtils.isEmpty(LocalLogin.getInstance().mSid)) {
                    StorageData storageData = new StorageData(LocalLogin.getInstance().mPhoneNum, LocalLogin.getInstance().mSid);
                    storageData.writeIn(mmContext, "key.obj");
                } else {
                    if (mmCallback != null)
                        mmCallback.arg1 = ERR_LOGIN;
                }

            } catch (JSONException e) {
                if (mmCallback != null)
                    mmCallback.arg1 = ERROR_PARSE;
            }

            if (mmCallback != null)
                mmCallback.sendToTarget();
        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    /**
     * 登陆后的处理
     *
     * @param msg
     */
    private void handleLoginDone(Message msg) {
        if (msg.arg1 == 0) {
            LocalLogin.getInstance().login(mContext);
//            getEventsList("0", 1);
//            getCloudGroupList();
            getRongToken();
        } else {
            httpReqDlgDismiss();
            String str = "";
            if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                str = getString(R.string.active_failure_no_network);
            } else {
                str = (String) msg.obj;
            }
            mDialog.titleMsgBtnStyle("登录失败", str, "确定");
            mDialog.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                @Override
                public void onConfirmClick(Dialog lDialog) {
                    lDialog.dismiss();
                }

                @Override
                public void onCancelClick(Dialog lDialog) {

                }
            });
        }
    }


    private void httpReqDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**
     * 用于监听软键盘弹出和隐藏的接口
     */
    private class MyResizeListener implements ResizeLinerLayout.OnResizeListener {
        @Override
        public void onResize(int w, int h, int oldw, int oldh) {
            int change = BIGGER;
            if (h < oldh) {
                change = SMALLER;
                mPreferenceUtil.save("key_board_h", oldh - h);
            }
            Message message = Message.obtain();
            message.what = MSG_RESIZE;
            message.arg1 = change;
            mHandler.sendMessage(message);
        }
    }


    /**
     * 获取事件列表
     *
     * @param type 事件类型 0. 全部, 1：公告，2：审批，3：周报，4：普通事件，5：自定义  6:系统事件  7：活动 8：投票 9:签到
     */
    public void getEventsList(String type, int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, type));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        EventDataMessage.GetEventListData eventListData = new EventDataMessage.GetEventListData(mHandler.obtainMessage(MSG_GET_EVENT_LIST), mContext, type, 1);
        eventListData.mApi = AsynHttpClient.API_EVENT_LIST_V3;
        eventListData.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execEventHttp(eventListData);
    }


    /**
     * 获取团队列表
     */
    public void getCloudGroupList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetGroupListMsg getGroup = new GetGroupListMsg(mContext, mHandler.obtainMessage(MSG_GET_CLOUD_GROUP_LIST));
        getGroup.mApi = AsynHttpClient.API_GROUP_GETLIST;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execCcHttp(getGroup);
    }

    /**
     * 绑定极光推送唯一 id
     * @param registrationId
     */
    private void setRegistrationId(String registrationId) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair("registration_id", registrationId));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_SET_REGISTRATION_ID));
        message.mApi = AsynHttpClient.API_APP_ANDROID_PUSH;
        message.mParams = mList;
        AsynHttpClient.getInstance(mContext).execUserHttp(message);

    }


}
